package com.cgnpc.cuddemo.workbench.controller;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cgnpc.cud.annotation.OperatorType;
import com.cgnpc.cud.annotation.UBA;
import com.cgnpc.cud.auth.vo.Menu;
import com.cgnpc.cud.core.common.util.JSONUtils;
import com.cgnpc.cud.core.controller.BaseController;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cud.shiro.util.ContextHolder;
import com.cgnpc.cuddemo.workbench.application.IPermissonApplication;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.config.MockClient;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/******************************
 * 用途说明: uau权限 前端控制器
 * 作者姓名: PXMWRYA
 * 创建时间: 2019/07/19 09:14
 ******************************/
@RestController
@RequestMapping("/uau/perm")
public class PermissonController extends BaseController {

    @Autowired
    IPermissonApplication iPermissonApplication;

    private String devMode;

    @Autowired
    private MockClient mockClient;

    @Value("${spring.profiles.usemock}")
    private void setDevMode(String dm) {
        devMode = dm;
    }

    /**********************************
     * 用途说明:获取用户的菜单权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getMenuPermission")
//    @UBA(module = "权限模块", action = "调用UAU获取菜单资源", channel = OperatorType.Page)
    public AjaxResult getMenuPermission() {
        try {
            if ("local".equals(devMode)) {
                HashSet<Menu> menus = new HashSet();
                String json = PermissonInfoController.getMenuPermissionJsonWithLocalTest();
                ApiResult result = JacksonUtil.readValue(json, ApiResult.class);
                JSONObject jsonObject = JSONUtils.fromObject(result);

                if ("200".equals(jsonObject.getString("code"))) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    jsonArray.forEach((o) -> {
                        JSONObject object = (JSONObject) o;
                        if ("001".equals(object.getString("type")) || "002".equals(object.getString("type"))) {
                            Menu menu = new Menu();
                            menu.setMenuCode(object.getString("menuCode"));
                            menu.setMenuId(object.getString("funcCode"));
                            menu.setMenuName(object.getString("funcaction"));
                            menu.setUrl(object.getString("furl"));
                            menu.setNumUrl(object.getString("numUrl"));
                            menu.setMenuType(object.getString("type"));
                            menu.setOrderNum(object.getString("orderNo"));
                            menu.setParentId(object.getString("parentsId"));
                            menu.setEnglishName(object.getString("byName"));
                            menus.add(menu);
                        }

                    });
                    return getObject(menus);
                }
            }
            Set<Menu> menuSet = iPermissonApplication.selectMenus(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            return getObject(menuSet);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**********************************
     * 用途说明:获取用户的菜单权限(树形，用户前端显示)
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getMenuPermissionTree")
//    @UBA(module = "权限模块", action = "获取用户的菜单权限(树形，用户前端显示)", channel = OperatorType.Page)
    public AjaxResult getMenuPermissionTree(HttpServletRequest request) {
        try {
            if ("local".equals(devMode)) {
                String json = PermissonInfoController.getMenuPermissionTreeJsonWithLocalTest();

                HashSet<Menu> menus = new HashSet();
                ApiResult result = JacksonUtil.readValue(json, ApiResult.class);
                JSONObject jsonObject = JSONUtils.fromObject(result);

                if ("200".equals(jsonObject.getString("code"))) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    jsonArray.forEach((o) -> {
                        JSONObject object = (JSONObject) o;
                        if ("001".equals(object.getString("type")) || "002".equals(object.getString("type"))) {
                            Menu menu = new Menu();
                            menu.setMenuCode(object.getString("menuCode"));
                            menu.setMenuId(object.getString("funcCode"));
                            menu.setMenuName(object.getString("funcaction"));
                            menu.setUrl(object.getString("furl"));
                            menu.setNumUrl(object.getString("numUrl"));
                            menu.setMenuType(object.getString("type"));
                            menu.setOrderNum(object.getString("orderNo"));
                            menu.setParentId(object.getString("parentsId"));
                            menu.setEnglishName(object.getString("byName"));
                            menus.add(menu);
                        }

                    });

                    Set<Menu> collect = menus.stream().filter(menu -> "001".equals(menu.getMenuType())).collect(Collectors.toSet());
                    List<Menu> menuList = iPermissonApplication.menuToTree(collect);
                    return getObject(menuList);
                }

//                AjaxResult invoke = mockClient.invoke("testServiceImpl", "test1", null, AjaxResult.class);

//                List l = new ArrayList();
//                l.add("params");
//                AjaxResult invoke = mockClient.invoke("testServiceImpl", "test2", l, AjaxResult.class,String.class);

//                Map m = new HashMap();
//                m.put("p1","aaa");
//                m.put("p2","bbb");
//                List l = new ArrayList();
//                l.add(m);
//                AjaxResult invoke = mockClient.invoke("testServiceImpl", "test3", l, AjaxResult.class, Map.class);


//                Map m = new HashMap();
//                m.put("p1","aaa");
//                m.put("p2","bbb");
//                List l = new ArrayList();
//                l.add("bbbbbbbbbb");
//                l.add(m);
//                AjaxResult invoke = mockClient.invoke("testServiceImpl", "test4", l, AjaxResult.class, String.class,Map.class);

//                AjaxResult invoke = mockClient.invoke(request,"permissonController", "getMenuPermissionTree", null, AjaxResult.class,HttpServletRequest.class);
//                return invoke;

            }
            List<Menu> menuList = iPermissonApplication.selectMenusTree(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            return getObject(menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**********************************
     * 用途说明:获取用户的叶子节点菜单(用户显示常用功能)
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getMenuPermissionTreeLeaf")
//    @UBA(module = "权限模块", action = "获取用户的菜单权限(树形，用户前端显示)", channel = OperatorType.Page)
    public AjaxResult getMenuPermissionTreeLeaf(@RequestBody Menu params) {
        try {
            if ("local".equals(devMode)) {
                String json = PermissonInfoController.getMenuPermissionTreeJsonWithLocalTest();

                HashSet<Menu> menus = new HashSet();
                ApiResult result = JacksonUtil.readValue(json, ApiResult.class);
                JSONObject jsonObject = JSONUtils.fromObject(result);

                if ("200".equals(jsonObject.getString("code"))) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    jsonArray.forEach((o) -> {
                        JSONObject object = (JSONObject) o;
                        if ("001".equals(object.getString("type")) || "002".equals(object.getString("type"))) {
                            Menu menu = new Menu();
                            menu.setMenuCode(object.getString("menuCode"));
                            menu.setMenuId(object.getString("funcCode"));
                            menu.setMenuName(object.getString("funcaction"));
                            menu.setUrl(object.getString("furl"));
                            menu.setNumUrl(object.getString("numUrl"));
                            menu.setMenuType(object.getString("type"));
                            menu.setOrderNum(object.getString("orderNo"));
                            menu.setParentId(object.getString("parentsId"));
                            menu.setEnglishName(object.getString("byName"));
                            menus.add(menu);
                        }

                    });

                    Set<Menu> collect = menus.stream().filter(menu -> "001".equals(menu.getMenuType())).collect(Collectors.toSet());
                    List<Menu> menuList = iPermissonApplication.menuToTree(collect);

                    List<Menu> leafs = new ArrayList<>();
                    filterLeaf(menuList,leafs);
                    if(!StringUtil.isNullOrSpace(params.getMenuName())) {
                        List<Menu> collect2 = leafs.stream().filter(menu -> (menu.getMenuName() !=null && menu.getMenuName().indexOf(params.getMenuName())>-1)).collect(Collectors.toList());
                        return getObject(collect2);
                    }

                    return getObject(leafs);
                }
            }
            List<Menu> menuList = iPermissonApplication.selectMenusTree(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            List<Menu> leafs = new ArrayList<>();
            filterLeaf(menuList,leafs);
            if(!StringUtil.isNullOrSpace(params.getMenuName())) {
                List<Menu> collect = leafs.stream().filter(menu -> "001".equals(params.getMenuName())).collect(Collectors.toList());
                return getObject(collect);
            }

            return getObject(leafs);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    private List<Menu> filterLeaf(List<Menu> menuList,List<Menu> result) {
        for(Menu menu : menuList) {
            if(menu.getChildren() == null || menu.getChildren().size() == 0) {
                result.add(menu);
            } else {
                filterLeaf(menu.getChildren(),result);
            }
        }
        return menuList;
    }

    /**********************************
     * 用途说明:获取用户的其他权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getPermissions")
//    @UBA(module = "权限模块", action = "调用UAU获取资源", channel = OperatorType.Page)
    public AjaxResult getPermissions() {
        try {
            Set<String> permSet = iPermissonApplication.selectPermissions(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            return getObject(permSet);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**********************************
     * 用途说明:获取用户的角色
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getRoles")
//    @UBA(module = "权限模块", action = "调用UAU获取角色", channel = OperatorType.Page)
    public AjaxResult getRoles() {
        try {
            Set<String> permSet = iPermissonApplication.selectRoles(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            return getObject(permSet);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**********************************
     * 用途说明:获取读写权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @PostMapping("/getWritePermission")
//    @UBA(module = "权限模块", action = "获取读写权限", channel = OperatorType.Page)
    public AjaxResult getWritePermission() {
        try {
            if ("local".equals(devMode)) {
                String json = PermissonInfoController.getMenuPermissionTreeJsonWithLocalTest();

                HashSet<Menu> menus = new HashSet();
                ApiResult result = JacksonUtil.readValue(json, ApiResult.class);
                JSONObject jsonObject = JSONUtils.fromObject(result);

                if ("200".equals(jsonObject.getString("code"))) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    jsonArray.forEach((o) -> {
                        JSONObject object = (JSONObject) o;
                        if ("001".equals(object.getString("type")) || "002".equals(object.getString("type"))) {
                            Menu menu = new Menu();
                            menu.setMenuCode(object.getString("menuCode"));
                            menu.setMenuId(object.getString("funcCode"));
                            menu.setMenuName(object.getString("funcaction"));
                            menu.setUrl(object.getString("furl"));
                            menu.setNumUrl(object.getString("numUrl"));
                            menu.setMenuType(object.getString("type"));
                            menu.setOrderNum(object.getString("orderNo"));
                            menu.setParentId(object.getString("parentsId"));
                            menu.setEnglishName(object.getString("byName"));
                            menus.add(menu);
                        }

                    });

                    Set<Menu> collect = menus.stream().filter(menu -> "002".equals(menu.getMenuType())).collect(Collectors.toSet());
                    return getObject(collect);
                }

            }
            Set<Menu> menuList = iPermissonApplication.getWritePermission(ContextHolder.getPrincipalName(), ContextHolder.getProject());
            return getObject(menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

}